package com.example.campuslink.commen.dialog

import android.content.Context
import android.graphics.Bitmap
import android.os.Environment
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.campuslink.R
import com.example.campuslink.commen.core.CoreDialog
import com.example.campuslink.commen.db.userInfo.UserInfoDao
import com.example.campuslink.commen.db.userInfo.UserInfoData
import com.example.campuslink.commen.db.userInfo.UserInfoTable
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.databinding.DialogUserZxingBinding
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

class UserZxingDialog : CoreDialog<DialogUserZxingBinding>(R.layout.dialog_user_zxing) {
    private lateinit var userInfoDB: UserInfoData
    private lateinit var userInfoDao: UserInfoDao
    private var userInfoTable: UserInfoTable? = null
    private var bitmap: Bitmap? = null
    override fun setupViews() {
        val textToEncode = userInfoTable?.userNumber
        binding.tvTelNumber.text = textToEncode
        binding.tvUserName.text = userInfoTable?.userName
        Glide.with(requireContext()).load(userInfoTable?.userAvatar)
            .apply(RequestOptions.circleCropTransform())
            .into(binding.ivUserImg)
        val width = 500
        val height = 500
        try {
            val barcodeEncoder = BarcodeEncoder()
            bitmap = barcodeEncoder.encodeBitmap(
                textToEncode,
                BarcodeFormat.QR_CODE,
                500,
                500
            )
            binding.ivQrCodeImageView.setImageBitmap(bitmap)
        } catch (e: Exception) {
            e.printStackTrace()
            // 可以在此处添加错误处理，如显示默认图片
            binding.ivQrCodeImageView.setImageResource(R.drawable.ic_empty)
        }
        binding.layoutZxingDialog.setOnClickListener {
            bitmap?.let {
                saveImage(it)
                dismiss()
            }
        }
    }

    private fun saveImage(bitmap: Bitmap) {
        var imageFile: File? = null
        try {
            val storageDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            imageFile = File.createTempFile("dialog_image", ".jpg", storageDir)
            val fos = FileOutputStream(imageFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.close()

            Toast.makeText(requireContext(), "二维码已保存到: $imageFile", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "保存失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }


    override fun onAttach(context: Context) {
        super.onAttach(context)
        userInfoDB = UserInfoData.getDatabase(context.applicationContext)
        userInfoDao = userInfoDB.userInfoDao()
        lifecycleScope.launch(Dispatchers.IO) {
            userInfoTable = userInfoDao.getUserInfoByUserNumber(
                Sp.getString(context, "userNumber", "") ?: return@launch
            )
        }
    }

    override fun createBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): DialogUserZxingBinding {
        return DialogUserZxingBinding.inflate(inflater, container, false)
    }

    override fun handlerOnStart() {
        super.handlerOnStart()
        dialog?.setCancelable(true)
        dialog?.setCanceledOnTouchOutside(true)
    }
}